<template>
  <div>
    <h2>登录</h2>
    <form @submit.prevent="login">
      <div>
        <label for="username">用户名：</label>
        <input type="text" id="username" v-model="username" required>
      </div>
      <div>
        <label for="password">密码：</label>
        <input type="password" id="password" v-model="password" required>
      </div>
      <button type="submit">登录</button>
    </form>
    <p v-if="errorMessage" style="color: red;">{{ errorMessage }}</p>
  </div>
</template>

<script>
// 导入 Axios
import axios from 'axios';

export default {
  data() {
    return {
      username: '',
      password: '',
      errorMessage: ''
    };
  },
  methods: {
    async login() {
      try {
        // 发送登录请求
        const response = await axios.post('/api/login', {
          username: this.username,
          password: this.password
        });
        // 登录成功
        if (response.data.success) {
          // 跳转到首页或其他页面
          this.$router.push('/');
        } else {
          // 登录失败，显示错误信息
          this.errorMessage = response.data.message;
        }
      } catch (error) {
        // 处理登录请求失败的情况
        console.error('登录失败：', error);
        this.errorMessage = '登录失败，请稍后重试。';
      }
    }
  }
};
</script>